package com.sphd.education.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.JsonObject;
import com.sphd.education.EducationApplication;
import com.sphd.education.R;
import com.sphd.education.adapter.TagsAdapter;
import com.sphd.education.base.BaseActivity;
import com.sphd.education.info.LessonInfo;
import com.sphd.education.info.MyInfo;
import com.sphd.education.modle.EducationUrl;
import com.sphd.education.utils.ToastUtils;
import com.sphd.education.view.MyGridView;

import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
/**
 * 评价界面
 */

public class LessonMyEvaluationActivity extends BaseActivity implements RatingBar.OnRatingBarChangeListener, View.OnClickListener, RadioGroup.OnCheckedChangeListener, CompoundButton.OnCheckedChangeListener {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.lesson_school_name)
    TextView lessonSchoolName;
    @Bind(R.id.lesson_lesson_name)
    TextView lessonLessonName;
    @Bind(R.id.lesson_class_name)
    TextView lessonClassName;
    @Bind(R.id.lesson_lesson_time)
    TextView lessonLessonTime;
    @Bind(R.id.lesson_lesson_state)
    TextView lessonLessonState;
    @Bind(R.id.one_ratingbar)
    RatingBar oneRatingbar;
    @Bind(R.id.one_score)
    TextView oneScore;
    @Bind(R.id.two_ratingbar)
    RatingBar twoRatingbar;
    @Bind(R.id.two_score)
    TextView twoScore;
    @Bind(R.id.three_ratingbar)
    RatingBar threeRatingbar;
    @Bind(R.id.three_score)
    TextView threeScore;
    @Bind(R.id.my_comment)
    EditText myComment;
    @Bind(R.id.good_evaluation)
    RadioButton goodEvaluation;
    @Bind(R.id.middle_evaluation)
    RadioButton middleEvaluation;
    @Bind(R.id.bad_evaluation)
    RadioButton badEvaluation;
    @Bind(R.id.no_name_checkbox)
    CheckBox noNameCheckbox;
    @Bind(R.id.evaluation)
    Button evaluation;
    @Bind(R.id.radio_btns)
    RadioGroup radioBtns;
    String evaluationResult = "2";
    String noName = "yes";
    LessonInfo lessonInfo;
    String url;
    @Bind(R.id.my_gridView)
    MyGridView myGridView;
    TagsAdapter tagsAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lesson_my_evaluation);
        ButterKnife.bind(this);
        toolbar.setTitle("评价");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        initView();
    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        lessonInfo= (LessonInfo) bundle.getSerializable("listLesson");
        lessonSchoolName.setText(lessonInfo.getSchoolName());
        lessonLessonName.setText("课程:\t" + lessonInfo.getName());
        lessonClassName.setText("班级:\t" + lessonInfo.getBanji());
        lessonLessonTime.setText("课时:\t" + lessonInfo.getPeriod());
        switch (lessonInfo.getState()+"") {
            case "1":
                lessonLessonState.setText("状态:\t未开课");
                break;
            case "2":
                lessonLessonState.setText("状态:\t已开课");
                break;
            case "3":
                lessonLessonState.setText("状态:\t已结业");
                break;
            default:
                lessonLessonState.setText("状态:\t数据解析错误");
                break;
        }
        List<String> listtags =new ArrayList<>();
        listtags.add("讲解生动");
        listtags.add("风趣幽默");
        listtags.add("成绩渐长");
        listtags.add("启发学生");
        listtags.add("进步明显");
        listtags.add("耐心答疑");
        listtags.add("方法给力");
        listtags.add("备课充分");
        listtags.add("仪表整洁");
        listtags.add("上课准时");
        listtags.add("激情授课");
        listtags.add("调动兴趣");
        listtags.add("讲解透彻");
        listtags.add("准时开课");
        listtags.add("课后负责");
        listtags.add("讲法独到");
        tagsAdapter=new TagsAdapter(listtags);
        myGridView.setAdapter(tagsAdapter);
        myGridView.setVerticalSpacing(10);
        myGridView.setHorizontalSpacing(10);
        initEvent();
    }

    @Override
    public void findViewById() {
    }

    @Override
    public void myNet() {

    }

    private void initEvent() {
        oneRatingbar.setOnRatingBarChangeListener(this);
        twoRatingbar.setOnRatingBarChangeListener(this);
        threeRatingbar.setOnRatingBarChangeListener(this);
        radioBtns.setOnCheckedChangeListener(this);
        evaluation.setOnClickListener(this);
        noNameCheckbox.setOnCheckedChangeListener(this);
    }

    @Override
    public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
        ToastUtils.MyToast(this, ratingBar + "" + "\n" + rating + "\n" + fromUser);

        switch (ratingBar.getId()) {
            case R.id.one_ratingbar:
                oneScore.setText(rating + "");
                break;
            case R.id.two_ratingbar:
                twoScore.setText(rating + "");
                break;
            case R.id.three_ratingbar:
                threeScore.setText(rating + "");
                break;
        }
    }
    public String turnUtf8(String text){
        String s=null;
        try {
           s= URLEncoder.encode(text, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;
    }
    @Override
    public void onClick(View v) {
        evaluation.setClickable(false);
        MyInfo myInfo= DataSupport.findLast(MyInfo.class);
        List<String> list = tagsAdapter.getStringList();

        StringBuffer stringBuffer =new StringBuffer();
        for (int i=0;i<list.size();i++){
            stringBuffer.append(list.get(i));
        }

        if (noName.equals("yes")){
            url=EducationUrl.HttpTitle+EducationUrl.MyEvaluate+"tag="+turnUtf8(stringBuffer.toString()) +"&oId="+
                    lessonInfo.getSchoolid()+"&classId="+lessonInfo.getLesson_id()+"&scoreQuality="+
                    oneScore.getText()+"&scoreEnvironment="+twoScore.getText()+"&scoreSchedule="+threeScore.getText()
                    +"&operatetype=" + evaluationResult+"&comment="+turnUtf8(myComment.getText().toString())+
                    "&studentId="+myInfo.getUserid()+"&anonymousType=0";
        }else {
            url=EducationUrl.HttpTitle+EducationUrl.MyEvaluate+"tag="+turnUtf8(stringBuffer.toString())+"&oId="+lessonInfo.getSchoolid()+"&classId="+lessonInfo.getLesson_id()+"&scoreQuality="+
                    oneScore.getText()+"&scoreEnvironment="+twoScore.getText()+"&scoreSchedule="+threeScore.getText()
                    +"&operatetype=" + evaluationResult+"&comment="+turnUtf8(myComment.getText().toString())+"&studentId="+myInfo.getUserid()+"&anonymousType=1";
        }
        Log.e("url", url);
        StringRequest stringRequest =new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("yesorno",response);
                if (response.equals("yes")){
                    ToastUtils.MyToast(LessonMyEvaluationActivity.this,"上传成功。");
                    finish();
                }else if (response.equals("re")){
                    ToastUtils.MyToast(LessonMyEvaluationActivity.this,"Sorry，评价次数已超过两次。");
                    finish();
                }else {
                    ToastUtils.MyToast(LessonMyEvaluationActivity.this,"上传失败，请重试。");
                    evaluation.setClickable(true);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("error",error.toString());
                evaluation.setClickable(true);
            }
        });
        EducationApplication.getRequestQueue().add(stringRequest);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_lesson_my_eva, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == android.R.id.home) {

            finish();
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.good_evaluation:
                evaluationResult = "3";
                break;
            case R.id.middle_evaluation:
                evaluationResult = "2";
                break;
            case R.id.bad_evaluation:
                evaluationResult = "1";
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            noName = "no";
        } else {
            noName = "yes";
        }
    }
}
